package com.moyv.schoolbbs.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;


import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.moyv.schoolbbs.R;
import com.moyv.schoolbbs.ui.adapter.GridViewAdapter;
import com.moyv.schoolbbs.util.UIHelper;
import com.moyv.schoolbbs.ui.config.MainConstant;
import com.moyv.schoolbbs.config.PictureSelectorConfig;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.moyv.schoolbbs.config.AccountConstant.ACCOUNT;
import static com.moyv.schoolbbs.config.AccountConstant.TOKEN;
import static com.moyv.schoolbbs.config.URLConstant.RELPOST_URL;
import static com.moyv.schoolbbs.service.PictureService.uploading;
import static com.moyv.schoolbbs.ui.config.MainConstant.ADD_SHOW;
import static com.moyv.schoolbbs.ui.config.MainConstant.SHOW;
import static com.moyv.schoolbbs.util.HttpUtil.createClient;
import static com.moyv.schoolbbs.util.UIHelper.showDialogForLoading;

public class AddActivity extends AppCompatActivity {
    private static final int SUCCESS = 0;
    private static final int FALL = 404;
    private static final String TAG = "AddActivity";
    private Context mContext;
    private GridView gridView;
    private LinearLayout btnBack;
    private TextView btnPush;
    private EditText etPost;
    /**
     * 上传的图片凭证的数据源
     */
    private ArrayList<String> mPicList = new ArrayList<>();
    /**
     * 展示上传的图片的适配器
     */
    private GridViewAdapter mGridViewAddImgAdapter;
    private UIHelper uiHelper;
    private int okPostId;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    UIHelper.closeDialog(mContext);
                    Toast.makeText(AddActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, BottomTabLayoutActivity.class);
                    startActivity(intent);
                    break;
                case FALL:
                    UIHelper.closeDialog(mContext);
                    Toast.makeText(AddActivity.this, "发表失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        setContentView(R.layout.activity_add);
        uiHelper = new UIHelper();
        etPost = findViewById(R.id.et_post);
        btnBack = findViewById(R.id.btn_back);
        btnPush = findViewById(R.id.btn_push);

        mContext = this;
        gridView = findViewById(R.id.gridView);

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AddActivity.this, BottomTabLayoutActivity.class);
                startActivity(intent);
            }
        });
        btnPush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialogForLoading(mContext, "发表中");
                relPost();
            }
        });
        initGridView();
    }

    /**
     * 初始化展示上传图片的GridView
     */

    private void initGridView() {
        mGridViewAddImgAdapter = new GridViewAdapter(mContext, mPicList);
        gridView.setAdapter(mGridViewAddImgAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (position == parent.getChildCount() - 1) {
                    //如果“增加按钮形状的”图片的位置是最后一张，且添加了的图片的数量不超过5张，才能点击
                    if (mPicList.size() == MainConstant.MAX_SELECT_PIC_NUM) {
                        //最多添加5张图片
                        viewPluImg(position);
                    } else {
                        //添加凭证图片
                        selectPic(MainConstant.MAX_SELECT_PIC_NUM - mPicList.size());
                    }
                } else {
                    viewPluImg(position);
                }
            }
        });
    }

    /**
     * 查看大图
     * @param position 点击图片的索引值3
     */

    private void viewPluImg(int position) {
        Intent intent = new Intent(mContext, PlusImageActivity.class);
        intent.putExtra(SHOW, ADD_SHOW);
        intent.putStringArrayListExtra(MainConstant.IMG_LIST, mPicList);
        intent.putExtra(MainConstant.POSITION, position);
        startActivityForResult(intent, MainConstant.REQUEST_CODE_MAIN);
    }

    /**
     * 打开相册或者照相机选择凭证图片，最多5张
     *
     * @param maxTotal 最多选择的图片的数量
     */
    private void selectPic(int maxTotal) {
        PictureSelectorConfig.initMultiConfig(this, maxTotal);
    }

    /**
     * 处理选择的照片的地址
     */
    private void refreshAdapter(List<LocalMedia> picList) {
        for (LocalMedia localMedia : picList) {
            //被压缩后的图片路径
            if (localMedia.isCompressed()) {
                //压缩后的图片路径
                String compressPath = localMedia.getCompressPath();
                //把图片添加到将要上传的图片数组中
                mPicList.add(compressPath);
                System.out.println(mPicList);
                mGridViewAddImgAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    refreshAdapter(PictureSelector.obtainMultipleResult(data));
                    break;
            }
        }
        if (requestCode == MainConstant.REQUEST_CODE_MAIN && resultCode == MainConstant.RESULT_CODE_VIEW_IMG) {
            //查看大图页面删除了图片
            //要删除的图片的集合
            ArrayList<String> toDeletePicList = data.getStringArrayListExtra(MainConstant.IMG_LIST);
            mPicList.clear();
            mPicList.addAll(toDeletePicList);
            mGridViewAddImgAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 发布帖子请求处理
     */

    public void relPost() {
        String url = RELPOST_URL;
        int account = ACCOUNT;
        String content = etPost.getText().toString();
        int type = mPicList.size();
        JSONObject obj = new JSONObject();
        try {
            obj.put("account", account);
            obj.put("content", content);
            obj.put("type", type);
        } catch (JSONException e) {
            System.out.println("AddActivity.rePost:Json数据处理错误");
        }

        OkHttpClient okHttpClient = createClient();
//        请求体
        FormBody formBody = new FormBody.Builder()
                .add("token", String.valueOf(TOKEN))
                .add("result", obj.toString())
                .build();
        Request request = new Request.Builder()
                .post(formBody)
                .url(url)
//                .addHeader("application/json", "charset=utf-8")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
//                访问失败
                handler.sendMessage(handler.obtainMessage(404));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String resp = response.body().string();
                System.out.println(resp);
                try {
                    JSONObject obj = new JSONObject(resp);
                    String result = obj.getString("result");
                    int postId = obj.getInt("postId");
                    //                返回成功
                    Log.e(TAG, "onResponse: " + resp);
                    if (result.equals("1")) {
                        if(mPicList.size()==0){
                            handler.sendMessage(handler.obtainMessage(0));
                        }else{
//                            发表图片
                            okPostId = postId;
                            List<String> picUrls = new ArrayList<>();
                            List<File> files = new ArrayList<>();
                            for (int i = 0; i < mPicList.size(); i++) {
                                String photo = mPicList.get(i);
                                File file = new File(photo);
                                files.add(file);
                                System.out.println(photo);
                                String url = okPostId + "_" + i + ".jpg";
                                picUrls.add(url);
                            }
                            uploading(files, picUrls, okPostId, handler1);
                        }
                    } else {
                        handler.sendMessage(handler.obtainMessage(404));
                    }
                } catch (JSONException e) {
                    System.out.println("addActivity.relPost.enqueue:json格式解析报错");
                }
            }
        });
    }

    Handler handler1 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 200:
                    handler.sendMessage(handler.obtainMessage(0));
                    System.out.println("图片上传成功");
                    break;
                case 301:
                    System.out.println("上传失败");
                    break;
                case 404:
                    System.out.println("服务器出错");
                    break;
                default:
            }
            return false;
        }
    });


}
